<template>
	<view class="container">
		<!-- 空状态栏占位 -->
		<view class="status-bar"></view>
		
		<!-- 交易基本信息 -->
		<view class="transaction-info" v-if="transactionDetail">
			<view class="info-section">
				<view class="info-row">
					<text class="label">单号:</text>
					<text class="value">{{ transactionDetail.txNo }}</text>
				</view>
				<view class="info-row">
					<text class="label">业务类型:</text>
					<view class="tag business-type">{{ businessTypeDisplay }}</view>
				</view>
				<view class="info-row">
					<text class="label">类型:</text>
					<view class="tag transaction-type" :class="transactionDirection === 'inbound' ? 'inbound' : 'outbound'">
						{{ transactionTypeDisplay }}
					</view>
				</view>
				<view class="info-row">
					<text class="label">操作人:</text>
					<text class="value">{{ operatorNameDisplay }}</text>
				</view>
				<view class="info-row">
					<text class="label">仓库:</text>
					<text class="value">{{ transactionDetail.warehouseCode || '未知仓库' }}</text>
				</view>
				<view class="info-row">
					<text class="label">备注:</text>
					<text class="value">{{ transactionDetail.remark || '无' }}</text>
				</view>
				<view class="info-row">
					<text class="label">时间:</text>
					<text class="value">{{ timeDisplay }}</text>
				</view>
			</view>
		</view>
		
		<!-- 备件明细 -->
		<view class="transaction-info" v-if="transactionItems && transactionItems.length > 0">
			<view class="info-section">
				<view class="info-row">
					<text class="section-title">备件明细</text>
				</view>
				<!-- 循环展示每个备件项目 -->
			<template v-for="(item, index) in transactionItems">
				<!-- 备件基本信息行 -->
				<view class="info-row" :key="'item-' + index">
						<text class="label">备件编号:</text>
						<text class="value">{{ item.partNo || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="label">备件名称:</text>
						<text class="value">{{ item.partName || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="label">规格型号:</text>
						<text class="value">{{ item.specNo || '-' }}</text>
					</view>
					<view class="info-row">
						<text class="label">备件类型:</text>
						<text class="value">{{ getPartTypeName(item.partTypeCode) }}</text>
					</view>
					<view class="info-row">
						<text class="label">数量:</text>
						<text class="value">{{ item.quantity || 0 }}</text>
					</view>
					<view class="info-row">
						<text class="label">方向:</text>
						<view class="tag transaction-type" :class="item.direction && item.direction.toLowerCase() === 'inbound' ? 'inbound' : 'outbound'">
							{{ getDirectionName(item.direction) }}
						</view>
					</view>
					<view class="info-row">
						<text class="label">备注:</text>
						<text class="value">{{ item.remark || '-' }}</text>
					</view>
					<!-- 分隔线，最后一个不需要 -->
					<view class="separator" v-if="index < transactionItems.length - 1" :key="'separator-' + index"></view>
				</template>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view v-if="!loading && (!transactionDetail || !transactionItems || transactionItems.length === 0)" class="empty-state">
			<text class="empty-icon">📋</text>
			<text class="empty-text">暂无交易明细</text>
		</view>
		
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-state">
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 关闭按钮 -->
		<view class="close-button" @click="goBack">
			<text class="close-text">关闭</text>
		</view>
	</view>
</template>

<script>
	import { getTransaction } from '@/api/inventory/transaction.js'
	
	export default {
		data() {
			return {
				txNo: '',
				transactionType: 'outbound',
				transactionDetail: null,
				transactionItems: [],
				loading: false
			}
		},
		
	onLoad(options) {
		console.log('交易详情页面加载', options)
		if (options && options.txNo) {
			this.txNo = options.txNo
		}
		if (options && options.type) {
			this.transactionType = options.type
		}
		if (this.txNo) {
			this.loadTransactionDetail()
		} else {
			console.error('缺少交易单号参数')
			uni.showToast({
				title: '缺少交易单号',
				icon: 'none'
			})
		}
	},
		
		computed: {
		businessTypeDisplay() {
			const businessType = this.transactionDetail ? this.transactionDetail.bizRefType || this.transactionDetail.txType : null;
			if (!businessType) return '-';
			
			const typeMapping = {
				// 出库业务类型
				'REPAIR': '维修出库',
				'TRANSFER': '调拨出库',
				'MAINTENANCE': '维护出库',
				'SCRAP': '报废出库',
				'OUTBOUND': '出库',
				'OTHER': '其他出库',
				// 入库业务类型
				'INBOUND': '入库',
				'PURCHASE': '采购入库',
				'RETURN': '退货入库',
				'INVENTORY': '盘点入库',
				'INVENTORY_GAIN': '盘盈入库'
			};
			return typeMapping[businessType] || businessType;
		},
		
		transactionTypeDisplay() {
			const txType = this.transactionDetail ? this.transactionDetail.txType : null;
			if (!txType) return '出库';
			
			// 定义入库类型列表
			const inboundTypes = ['INBOUND', 'PURCHASE', 'RETURN', 'INVENTORY', 'INVENTORY_GAIN'];
			
			// 如果是入库类型，返回"入库"；否则返回"出库"
			return inboundTypes.includes(txType) ? '入库' : '出库';
		},
		
		transactionDirection() {
			const transactionDetail = this.transactionDetail;
			if (!transactionDetail) return 'outbound';
			
			// 定义入库类型列表
			const inboundTypes = ['INBOUND', 'PURCHASE', 'RETURN', 'INVENTORY', 'INVENTORY_GAIN'];
			if (inboundTypes.includes(transactionDetail.txType)) {
				return 'inbound';
			}
			
			return this.transactionType === 'inbound' ? 'inbound' : 'outbound';
		},
			
			operatorNameDisplay() {
				const transactionDetail = this.transactionDetail;
				if (!transactionDetail) return '系统';
				
				if (transactionDetail.operator_name) return transactionDetail.operator_name;
				if (transactionDetail.operatorName) return transactionDetail.operatorName;
				if (transactionDetail.operator) return transactionDetail.operator;
				if (transactionDetail.operatorId) return `用户${transactionDetail.operatorId}`;
				if (transactionDetail.createBy) return `创建者${transactionDetail.createBy}`;
				return '系统';
			},
			
			timeDisplay() {
				const timeString = this.transactionDetail ? this.transactionDetail.createdAt || this.transactionDetail.createTime : null;
				if (!timeString) return '未知时间';
				
				try {
					let date;
					if (timeString.includes('T')) {
						date = new Date(timeString);
					} else if (timeString.includes(' ')) {
						const parts = timeString.split(' ');
						if (parts.length === 2) {
							date = new Date(`${parts[0]}T${parts[1]}`);
						} else {
							date = new Date(timeString);
						}
					} else {
						date = new Date(timeString);
					}
					
					if (isNaN(date.getTime())) return '未知时间';
					
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					const seconds = String(date.getSeconds()).padStart(2, '0');
					return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
				} catch (error) {
					return '未知时间';
				}
			}
		},
		
		methods: {
			// 加载交易详情
			async loadTransactionDetail() {
				try {
					this.loading = true
					console.log('开始加载交易详情:', this.txNo)
					
					const response = await getTransaction(this.txNo)
					console.log('交易详情API返回:', response)
					
					if (response.code === 200) {
						this.transactionDetail = response.data
						this.transactionItems = response.data.transactionItems || []
						console.log('交易详情加载完成:', this.transactionDetail)
						console.log('备件明细:', this.transactionItems)
						this.$forceUpdate()
					} else {
						uni.showToast({
							title: response.msg || '加载失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('加载交易详情失败:', error)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
				}
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack();
			},
			
		// 获取方向名称
		getDirectionName(direction) {
			if (!direction) return '出库';
			
			// 定义入库方向列表
			const inboundDirections = ['IN', 'INBOUND', 'PURCHASE', 'RETURN', 'INVENTORY', 'INVENTORY_GAIN'];
			const outboundDirections = ['OUT', 'OUTBOUND', 'REPAIR', 'TRANSFER', 'SCRAP', 'MAINTENANCE'];
			
			const upperDirection = direction.toUpperCase();
			
			if (inboundDirections.includes(upperDirection)) {
				return '入库';
			} else if (outboundDirections.includes(upperDirection)) {
				return '出库';
			}
			
			return '出库'; // 默认返回出库
		},
		
		// 获取方向样式类
		getDirectionClass(direction) {
			if (!direction) return 'outbound';
			
			const inboundDirections = ['IN', 'INBOUND', 'PURCHASE', 'RETURN', 'INVENTORY', 'INVENTORY_GAIN'];
			return inboundDirections.includes(direction.toUpperCase()) ? 'inbound' : 'outbound';
		},
			
			// 获取备件类型名称
			getPartTypeName(partTypeCode) {
				if (!partTypeCode) return '未知';
				
				const typeMapping = {
					'BEARING': '轴承',
					'SEAL': '密封件',
					'FILTER': '过滤器',
					'BELT': '皮带',
					'CHAIN': '链条',
					'GEAR': '齿轮',
					'VALVE': '阀门',
					'PUMP': '泵',
					'MOTOR': '电机',
					'SENSOR': '传感器',
					'CONTROLLER': '控制器',
					'OTHER': '其他'
				};
				
				return typeMapping[partTypeCode] || partTypeCode;
			},

			// 获取交易类型名称
			getTransactionTypeName(txType) {
				if (!txType) return '出库';

				const typeMapping = {
					'REPAIR': '出库',
					'TRANSFER': '出库',
					'MAINTENANCE': '出库',
					'SCRAP': '出库',
					'OTHER': '出库',
					'INBOUND': '入库',
					'OUTBOUND': '出库',
					'PURCHASE': '入库'
				};
				return typeMapping[txType] || '出库';
			},

			// 获取交易方向
			getTransactionDirection(transactionDetail) {
				if (!transactionDetail) return 'outbound';

				const inboundTypes = ['INBOUND', 'PURCHASE'];
				if (inboundTypes.includes(transactionDetail.txType)) {
					return 'inbound';
				}
				return 'outbound';
			},

			// 获取操作人名称
			getOperatorName(transactionDetail) {
				if (!transactionDetail) return '系统';

				if (transactionDetail.operator_name) return transactionDetail.operator_name;
				if (transactionDetail.operatorName) return transactionDetail.operatorName;
				if (transactionDetail.operator) return transactionDetail.operator;
				if (transactionDetail.operatorId) return `用户${transactionDetail.operatorId}`;
				if (transactionDetail.createBy) return `创建者${transactionDetail.createBy}`;
				return '系统';
			},

			// 格式化时间
			formatTime(timeString) {
				if (!timeString) return '未知时间';

				try {
					let date;
					if (timeString.includes('T')) {
						date = new Date(timeString);
					} else if (timeString.includes(' ')) {
						const parts = timeString.split(' ');
						if (parts.length === 2) {
							date = new Date(`${parts[0]}T${parts[1]}`);
						} else {
							date = new Date(timeString);
						}
					} else {
						date = new Date(timeString);
					}
					
					if (isNaN(date.getTime())) return '未知时间';
					
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					const hours = String(date.getHours()).padStart(2, '0');
					const minutes = String(date.getMinutes()).padStart(2, '0');
					const seconds = String(date.getSeconds()).padStart(2, '0');
					const result = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
					return result;
				} catch (error) {
					return '未知时间';
				}
			},

			// 获取方向类名（静态方法，用于模板）
			getDirectionClassStatic(direction) {
				if (!direction) return 'outbound';
				return direction.toLowerCase() === 'inbound' ? 'inbound' : 'outbound';
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
	}
	
	.status-bar {
		height: 20px;
		background-color: #4a94ff;
	}
	
	.transaction-info {
		margin: 20px;
		background-color: white;
		border-radius: 8px;
		padding: 20px;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}
	
	.info-section {
		display: flex;
		flex-direction: column;
		gap: 12px;
	}
	
	.info-row {
		display: flex;
		align-items: center;
		gap: 10px;
	}
	
	.label {
		font-size: 14px;
		color: #666;
		min-width: 80px;
	}
	
	.value {
		font-size: 14px;
		color: #333;
		flex: 1;
	}
	
	.tag {
		padding: 4px 8px;
		border-radius: 4px;
		font-size: 12px;
		color: white;
	}
	
	.business-type {
		background-color: #1890ff;
		border: 1px solid #1890ff;
	}
	
	.transaction-type.inbound {
		background-color: #52c41a;
		border: 1px solid #52c41a;
	}
	
	.transaction-type.outbound {
		background-color: #f5222d;
		border: 1px solid #f5222d;
	}
	
	.section-title {
		font-size: 16px;
		font-weight: bold;
		color: #333;
		margin-bottom: 15px;
	}
	
	.separator {
		height: 1px;
		background-color: #f0f0f0;
		margin: 20px 0;
	}
	
	.direction-tag.inbound {
		background-color: #52c41a;
		border: 1px solid #52c41a;
	}
	
	.direction-tag.outbound {
		background-color: #f5222d;
		border: 1px solid #f5222d;
	}
	
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60px 20px;
	}
	
	.empty-icon {
		font-size: 48px;
		margin-bottom: 15px;
		opacity: 0.5;
	}
	
	.empty-text {
		font-size: 16px;
		color: #999;
	}
	
	.loading-state {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 60px 20px;
	}
	
	.loading-text {
		font-size: 16px;
		color: #666;
	}
	
	.close-button {
		position: fixed;
		bottom: 30px;
		right: 30px;
		background-color: #4a94ff;
		color: white;
		padding: 12px 24px;
		border-radius: 20px;
		font-size: 14px;
		box-shadow: 0 2px 8px rgba(0,0,0,0.2);
	}
</style>